#include <iostream>
#include <vector>

#include "StdAfx.h"
#include "PitchTracker.h"
#include "WaveletPitchProcessor.h"
#include "WaveSample.h"

PitchTracker::PitchTracker(const	unsigned	int	bufferSize,
							const	unsigned	int	samplingFrequency)
{
	processor = new WaveletPitchProcessor(bufferSize, samplingFrequency);
	lastPitch = 120;
}

PitchTracker::~PitchTracker(void)
{
	delete processor;
}

void PitchTracker::Analyze(Sample* sample, double amplitudeThreshold, double noiseThreshold, PitchAnalysis* analysis)
{
	if(analysis->pitchOut==NULL) analysis->pitchOut = new PitchOut();

	PitchOut* out = analysis->pitchOut;
	Sample* lpSample = sample->LowPass400Filter();
	processor->trackPitch(lpSample->data, amplitudeThreshold, noiseThreshold, out);
	delete lpSample;
	if(!out->voiced || out->pitch<1)
	{
		/*
		if(out->signal_energy<1000)
		{
			analysis->frequency = 0;
			//lastPitch = 0;
		}
		else*/ {
			analysis->frequency = lastPitch;		
		}
		analysis->voiced = out->voiced;
		return;
	}
	//if(out->pitch<35) analysis->frequency = out->pitch * 4;
	/*if(out->pitch<100)*/ analysis->frequency = out->pitch * 2;	
	//analysis->frequency = out->pitch * 2;

	if(analysis->frequency<65) analysis->frequency = 0;
	else if(analysis->frequency>300) analysis->frequency = 0;
	else
	{		
		//int diff = abs(analysis->frequency-lastPitch);
		//if(diff < 50)
		{
			lastPitch = analysis->frequency;
		}
	}
	analysis->voiced = out->voiced;
}